import { ElMessageBox, messageType } from 'element-plus';

type ConfirmType = {
	title?: string;
	type?: messageType;
	message?: string;
	successCallback?: () => any;
};

export const useConfirm = ({
	title = '提示',
	type = 'warning',
	message = '',
	successCallback,
}: ConfirmType) => {
	let flags = true;
	ElMessageBox.confirm(message, title, {
		type: type,
		showCancelButton: true,
		confirmButtonText: '确定',
		cancelButtonText: '取消',
		beforeClose: async (action, instance, done) => {
			if (action === 'confirm') {
				flags = false;
				instance.confirmButtonLoading = true;
				instance.confirmButtonText = 'Loading...';
				try {
					successCallback && (await successCallback());
					done();
				} catch (error) {
					console.log(error);
				} finally {
					instance.confirmButtonLoading = false;
					instance.confirmButtonText = '确定';
					flags = true;
				}
			} else {
				if (flags) {
					done();
				}
			}
		},
	});
};
